package com.iqik.sc.ns.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.iqik.sc.ns.config.AuthCodeControllerHandler;
import com.iqik.sc.ns.service.AuthCodeService;
import com.iqik.sc.ns.service.EmailService;
import com.iqik.sc.ns.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/code")
public class AuthCodeController {

    @Reference(lazy = true)
    private AuthCodeService authCodeService;

    @Reference(lazy = true)
    private EmailService emailService;

    @Reference(lazy = true)
    private UserService userService;

    /**
     * /create/{email} true/false ⽣成验证码并发送到对应邮箱，成功true，失败
     */
    @RequestMapping("/create/{email}")
    @SentinelResource(value = "createCode", blockHandlerClass = AuthCodeControllerHandler.class,
            blockHandler = "createCodeBlockHandler", fallbackClass = AuthCodeControllerHandler.class,
            fallback = "createCodeFallback")
    public String createCode(@PathVariable(value = "email") String email) {
        if (userService.hadUser(email))
            return "false";
        System.out.println("code controller /code/create/{email}");
        return String.valueOf(emailService.sendCode(email, authCodeService.createAuthCode(email)));
    }

    /**
     * /code/validate/{email}/{code}
     * 校验验证码是否正确，0正确1错误2超时
     */
    @RequestMapping("/validate/{email}/{code}")
    @SentinelResource(value = "verityCode", blockHandlerClass = AuthCodeControllerHandler.class,
            blockHandler = "verityCodeBlockHandler", fallbackClass = AuthCodeControllerHandler.class,
            fallback = "verityCodeFallback")
    public String verityCode(@PathVariable(value = "email") String email,
                             @PathVariable(value = "code") String code) {

        return String.valueOf(authCodeService.verityAuthCode(email, code));
    }

}
